<?php

namespace App\Services\Order;

use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpKernel\Exception\HttpException;

class OrderContext
{
    /**
     * @var OrderOperation
     */
    private $operation;

    /**
     * 执行结果
     * @var
     */
    private $handleResult;

    /**
     * OrderContext constructor.
     * @param OrderOperation $operation
     */
    public function __construct(OrderOperation $operation)
    {
        $this->operation = $operation;
    }

    /**
     * @param null $order 下单时 是 null
     * @return $this
     * @throws \Throwable
     */
    public function excuteOperation($order = null)
    {
        try {
            \DB::beginTransaction();

            \Cache::lock(sprintf('AGENT_ID_%d_ORDER_CONTEXT_OPERATION', $order['agent_id'] ?? Auth::id()), 15)
                ->block(15, function () use ($order) {
                    $this->operation->beforeHandle($order);

                    $this->handleResult = $this->operation->handle($order);

                    $this->operation->afterHandle($order);
                });

            \DB::commit();
        } catch (LockTimeoutException $lockTimeoutException) {
            \DB::rollBack();

            abort(400, '服务器正忙,请稍后再试');
        } catch (HttpException $e) {
            throw $e;
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error(sprintf('用户订单操作发生错误: %s (%s[%d])', $e->getMessage(), $e->getFile(), $e->getLine()));

            abort(400, '下单出现错误,请重试或者联系我们,但这并不会影响您的资金');
        }

        return $this;
    }

    /**
     * @return mixed
     */
    public function getHandleResult()
    {
        return $this->handleResult;
    }
}
